<template>
  <div class="im-container">
    <!-- 左侧竖条：功能菜单 -->
    <LeftMenuBar
      ref="leftMenuBarRef"
      :current-user="currentUser"
      :active-menu="leftMenuActive"
      @menu-change="leftMenuActive = $event"
      @profile="handleShowProfile"
      @help="handleShowHelp"
      @logout="handleLogoutWrapper"
    />

    <!-- 中间层：根据左侧选择显示不同内容 -->
    <div class="middle-panel">
      <!-- 最近聊天 -->
      <Transition v-if="leftMenuActive === 'recent'" name="fade-slide" mode="out-in">
        <RecentChatList
          :key="'recent'"
          :search-query="searchQuery"
          :filtered-content="filteredMiddleContent"
          :current-target-id="currentTargetId"
          :get-last-message-time="getLastMessageTime"
          :get-last-message-preview="getLastMessagePreview"
          @update:search-query="searchQuery = $event"
          @select-user="selectUser"
          @select-group="(groupId, groupName) => selectGroup(groupId, groupName)"
          @delete-chat="handleDeleteChat"
          @view-group-members="handleViewGroupMembers"
          @add-friend-from-group="handleAddFriendFromGroup"
          @show-details="handleShowDetails"
          @create-group="handleCreateGroup"
        />
      </Transition>

      <!-- 好友列表 -->
      <Transition v-else-if="leftMenuActive === 'friends'" name="fade-slide" mode="out-in">
        <FriendsList
          :key="'friends'"
          :current-target-id="selectedFriendId"
          @select-friend="handleSelectFriendFromList"
          @show-friend-details="handleShowFriendDetailsFromList"
          @create-group="doCreateGroup"
        />
      </Transition>

    </div>

    <!-- 中间：聊天区域或用户详情面板 -->
    <div class="middle-chat-panel">
      <!-- 好友列表页面：显示用户详情面板 -->
      <div v-if="leftMenuActive === 'friends'" class="friend-details-panel">
        <div v-if="!selectedFriend" class="empty-chat">
          <div class="empty-chat-icon">
            <q-icon name="person_outline" size="80px" color="grey-4" />
          </div>
          <div class="empty-chat-text">
            <div class="empty-chat-title">选择一个联系人查看详情</div>
            <div class="empty-chat-hint">从左侧好友列表中选择一个联系人</div>
          </div>
        </div>
        <div v-else class="friend-details-content">
          <!-- 用户详情面板 -->
          <FriendDetailsPanel
            :friend="selectedFriend"
            @send-message="handleSendMessageToFriend"
            @update-remark="handleUpdateFriendRemark"
            @voice-call="handleVoiceCallFromFriend"
            @video-call="handleVideoCallFromFriend"
          />
        </div>
      </div>
      <!-- 其他页面：显示聊天窗口 -->
      <template v-else>
        <div v-if="!currentTargetId" class="empty-chat">
          <div class="empty-chat-icon">
            <q-icon name="chat_bubble_outline" size="80px" color="grey-4" />
          </div>
          <div class="empty-chat-text">
            <div class="empty-chat-title">选择一个聊天对象开始对话</div>
            <div class="empty-chat-hint">从左侧列表中选择好友或群组开始聊天</div>
          </div>
        </div>
        <!-- 聊天窗口（抽屉会覆盖在上面，不挤压布局） -->
        <div v-else class="chat-panel">
        <!-- 聊天头部 -->
        <ChatHeader
          :current-target-id="currentTargetId"
          :target-name="targetName"
          :target-type="chatStore.targetType"
          :get-user-initial="getUserInitial"
          :drawer-open="showDetailsDrawer"
          :member-count="currentMemberCount"
          @show-details="handleShowDetailsFromHeader"
          @voice-call="handleVoiceCall"
          @video-call="handleVideoCall"
          @group-call="handleShowGroupCallDialog"
        />

        <!-- 消息列表 -->
        <MessageList
          ref="messageListRef"
          :messages="currentMessages"
          :current-user-id="chatStore.currentUserId"
          :format-time="formatTime"
          :get-user-initial="getUserInitial"
          :get-user-name="getUserName"
          :chat-id="currentChatId"
          :chat-type="currentChatType"
          :chat-sequence="currentChatSequence"
          :read-sequence="currentReadSequence"
        />

        <!-- 输入区域 -->
        <MessageInput
          ref="messageInputRef"
          v-model:input-content="inputContent"
          v-model:show-emoji-picker="showEmojiPicker"
          :sending="sending"
          :selected-files="selectedFiles"
          :chat-type="currentChatType"
          :current-target-id="currentTargetId"
          :target-type="chatStore.targetType"
          :target-name="targetName"
          :get-user-initial="getUserInitial"
          @send="handleSendMessage"
          @enter-key="handleEnterKey"
          @shift-enter="handleShiftEnter"
          @file-select="handleFileSelect"
          @remove-file="handleRemoveFile"
          @emoji-select="handleEmojiSelect"
        />
        </div>
      </template>
    </div>


    <!-- 用户设置对话框 -->
    <UserSettings v-model="showSettings" @updated="handleUserUpdated" />

    <!-- 帮助对话框 -->
    <HelpDialog v-model="showHelp" />

    <!-- 添加联系人对话框 -->
    <AddContactDialog
      v-model="showAddContactDialog"
      :friends="availableFriendsForAdd"
      title="选择要添加的联系人"
      subtitle="选择要添加到群组中的联系人"
      @confirm="handleAddContactConfirm"
    />

    <!-- 视频通话对话框 -->
    <VideoCall
      v-model="showVideoCall"
      :target-user-id="videoCallTargetUserId || currentTargetId || ''"
      :target-name="videoCallTargetName || targetName"
      :current-user-id="chatStore.currentUserId || ''"
      :get-user-initial="getUserInitial"
      :is-voice-only="isVoiceCall"
      :is-group-call="isGroupCall"
      :group-members="groupCallMembers"
      @call-ended="handleCallEndedWrapper"
    />

    <!-- 详情抽屉（使用 q-dialog 实现，因为 q-drawer 需要 q-layout） -->
    <DetailsDrawer
      v-model="showDetailsDrawer"
      :type="detailsDrawerType"
      :target-id="detailsTargetId"
      :target-name="detailsTargetName"
      :do-not-disturb="doNotDisturb"
      :pin-chat="pinChat"
      :group-member-search="groupMemberSearch"
      :group-members="groupDrawerMembers"
      :group-details="currentGroupDrawerDetails"
      :show-all-members="showAllMembers"
      :is-group-owner="isGroupOwner"
      :group-chat-remark="groupChatRemark"
      :current-user-id="chatStore.currentUserId"
      :get-user-initial="getUserInitial"
      @add-contact="handleAddContact"
      @search-chat-history="handleSearchChatHistory"
      @update:doNotDisturb="handleToggleDoNotDisturb"
      @update:pinChat="handleTogglePinChat"
      @update:groupMemberSearch="groupMemberSearch = $event"
      @add-group-member="handleAddGroupMember"
      @remove-group-member="handleRemoveGroupMember"
      @show-remove-member-dialog="handleShowRemoveMemberDialog"
      @toggle-show-all-members="showAllMembers = !showAllMembers"
      @view-group-announcement="handleViewGroupAnnouncement"
      @dissolve-group="handleDissolveGroup"
      @leave-group="handleLeaveGroup"
      @clear-chat-history="handleClearChatHistory"
      @update-group-name="handleUpdateGroupName"
      @update-group-remark="handleUpdateGroupRemark"
    />

    <!-- 创建群组对话框 -->
    <CreateGroupDialog
      v-model="showCreateGroupDialog"
      :loading="creatingGroup"
      @create="doCreateGroup"
    />

    <!-- 添加好友对话框 -->
    <AddFriendDialog
      v-model="showUserDialog"
      :loading="searchingFriend"
      @add-friend="handleAddFriend"
    />

    <!-- 群组通话成员选择对话框 -->
    <GroupCallMemberDialog
      v-model="showGroupCallDialog"
      :members="groupCallMembers"
      @voice-call="handleGroupVoiceCall"
      @video-call="handleGroupVideoCall"
    />

    <!-- 通话邀请通知 -->
    <CallInviteNotification
      :invite-data="callInviteData"
      :get-user-initial="getUserInitial"
      @accept="handleCallInviteAccept"
      @reject="handleCallInviteReject"
      @timeout="handleCallInviteTimeout"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, nextTick, watch, computed } from 'vue'
import { useChatStore } from '../stores/chat'
import { useQuasar } from 'quasar'
import { chatWindow } from './ChatWindow'
import { getAvatarStyle } from '@/utils/avatar'
import { API_BASE_URL } from '@/config/env'
import LeftMenuBar from './LeftMenuBar.vue'
import RecentChatList from './RecentChatList.vue'
import ChatHeader from './ChatHeader.vue'
import MessageList from './MessageList.vue'
import MessageInput from './MessageInput.vue'
import FriendsList from './FriendsList.vue'
import UserSettings from './UserSettings.vue'
import UserMenu from './UserMenu.vue'
import HelpDialog from './HelpDialog.vue'
import AddContactDialog from './AddContactDialog.vue'
import GroupAvatar from './GroupAvatar.vue'
import VideoCall from './video-call/VideoCall.vue'
import FriendDetailsPanel from './FriendDetailsPanel.vue'
import DetailsPanel from './DetailsPanel.vue'
import DetailsDrawer from './DetailsDrawer.vue'
import CreateGroupDialog from './CreateGroupDialog.vue'
import AddFriendDialog from './AddFriendDialog.vue'
import GroupCallMemberDialog from './GroupCallMemberDialog.vue'
import CallInviteNotification from './CallInviteNotification.vue'

const $q = useQuasar()

const emit = defineEmits<{
  logout: []
}>()

// 使用业务逻辑
const chatWindowLogic = chatWindow()
const {
  // 状态
  fileInputRef,
  inputContentRef,
  inputContent,
  sending,
  showUserDialog,
  showEmojiPicker,
  newFriendForm,
  userList,
  friendList,
  recentChatUsers,
  selectedFiles,
  uploading,
  searchingFriend,
  searchQuery,
  leftMenuActive,
  showSettings,
  currentUser,
// 计算属性
  currentTargetId,
  currentMessages,
  connectionStatus,
  isConnected,
  targetName,
  middleContent,
  filteredMiddleContent,
  // 方法
  formatTime,
  getLastMessagePreview,
  getLastMessageTime,
  getUserInitial,
  getUserName,
  updateGroupMembersCache,
  updateGroupMemberAlias,
  scrollToBottom,
  selectUser,
  selectGroup,
  handleSend,
  handleEmojiSelect,
  handleEnterKey,
  handleShiftEnter,
  handleFileSelect,
  handleRemoveFile,
  handleAddFriend,
  handleLogout,
  handleVoiceCall,
  handleVideoCall,
  handleCallEnded: handleCallEndedFromLogic,
  showVideoCall,
  isVoiceCall,
  isGroupCall,
  showGroupCallDialog,
  groupCallMembers,
  videoCallTargetUserId,
  videoCallTargetName,
  callInviteData,
  handleGroupVoiceCall,
  handleGroupVideoCall,
  handleShowGroupCallDialog,
  handleCallInviteAccept,
  handleCallInviteReject,
  handleCallInviteTimeout,
  handleUserUpdated,
  handleDeleteChat,
  handleViewGroupMembers,
  handleAddFriendFromGroup,
  updateRecentChatUsers,
  init,
  cleanup,
  // UI 相关状态和计算属性（从 ChatWindow.vue 移入）
  currentChatId,
  currentChatType,
  currentChatSequence,
  currentReadSequence,
  currentMemberCount,
  groupMemberCountCache,
  GROUP_MEMBER_COUNT_CACHE_DURATION,
  currentGroupMemberCount,
  selectedFriend,
  selectedFriendId,
  showDetailsDrawer,
  detailsDrawerType,
  detailsTargetId,
  detailsTargetName,
  doNotDisturb,
  pinChat,
  groupMemberSearch,
  groupDrawerMembers,
  currentGroupDrawerDetails,
  showAllMembers,
  isGroupOwner,
  groupChatRemark,
  showUserMenu,
  showHelp,
  showAddContactDialog,
  availableFriendsForAdd,
  showCreateGroupDialog,
  creatingGroup,
  // UI 相关处理函数
  handleShowDetails,
  handleShowFriendDetails,
  handleSelectFriendFromList,
  handleShowFriendDetailsFromList,
  handleSendMessageToFriend,
  handleUpdateFriendRemark,
  handleVoiceCallFromFriend,
  handleVideoCallFromFriend,
  handleShowGroupDetailsFromList,
  loadGroupDrawerDetails,
  handleAddGroupMember,
  handleViewGroupAnnouncement,
  handleRemoveGroupMember,
  handleShowRemoveMemberDialog,
  handleUpdateGroupName,
  handleUpdateGroupRemark,
  handleSearchChatHistory,
  handleDissolveGroup,
  handleLeaveGroup,
  handleClearChatHistory,
  handleShowDetailsFromHeader,
  handleAddContact,
  handleAddContactConfirm,
  handleToggleDoNotDisturb,
  handleTogglePinChat,
  handleCreateGroup,
  doCreateGroup,
} = chatWindowLogic

// 组件引用（需要在 Vue 组件中使用）
const messageListRef = ref<InstanceType<typeof MessageList> | null>(null)
const messageInputRef = ref<InstanceType<typeof MessageInput> | null>(null)
const leftMenuBarRef = ref<InstanceType<typeof LeftMenuBar> | null>(null)

// 头像按钮引用
const avatarButtonRef = computed(() => {
  return leftMenuBarRef.value?.avatarButtonRef || null
})

// 包装 scrollToBottom 函数以使用新的 ref
const scrollToBottomWrapper = () => {
  if (messageListRef.value?.messagesContainerRef) {
    nextTick(() => {
      if (messageListRef.value?.messagesContainerRef) {
        const container = messageListRef.value.messagesContainerRef
        requestAnimationFrame(() => {
          container.scrollTop = container.scrollHeight
          setTimeout(() => {
            container.scrollTop = container.scrollHeight
            container.dispatchEvent(new Event('scroll'))
          }, 100)
        })
      }
    })
  } else {
    scrollToBottom()
  }
}

// 处理登出（包装函数，用于触发 emit）
const handleLogoutWrapper = async () => {
  await handleLogout()
  emit('logout')
}

// 用户菜单处理函数
const handleShowProfile = () => {
  showUserMenu.value = false
  showSettings.value = true
}

const handleShowHelp = () => {
  showUserMenu.value = false
  showHelp.value = true
}

// 处理通话结束（包装函数，用于清除临时通话目标）
const handleCallEndedWrapper = () => {
  videoCallTargetUserId.value = null
  videoCallTargetName.value = null
  handleCallEndedFromLogic()
}

// handleShowGroupCallDialog 已从 chatWindowLogic 解构，无需单独定义

// 所有处理函数已移至 ChatWindow.ts，以下代码已删除
// 如需查看实现，请参考 ChatWindow.ts

// 监听左侧菜单切换，清空当前选中的聊天目标
watch(leftMenuActive, (newMenu, oldMenu) => {
  if (newMenu !== oldMenu && oldMenu !== undefined) {
    chatStore.currentTargetId = null
    chatStore.targetType = 'User'
    if (newMenu !== 'friends') {
      selectedFriend.value = null
    }
    showDetailsDrawer.value = false
    inputContent.value = ''
    selectedFiles.value = []
  }
})

// 监听 currentTargetId 变化，确保切换聊天目标时关闭详情抽屉并清空输入框
watch(currentTargetId, (newTargetId, oldTargetId) => {
  if (newTargetId && newTargetId !== oldTargetId) {
    if (showDetailsDrawer.value) {
      showDetailsDrawer.value = false
    }
  } else if (!newTargetId && oldTargetId) {
    inputContent.value = ''
    selectedFiles.value = []
  }
})

// 添加发送消息的别名
const handleSendMessage = handleSend

const chatStore = useChatStore()

// 监听群组变化，异步获取最新的群组人数（必须在 chatStore 定义之后）
watch([currentTargetId, () => chatStore.targetType], async ([newId, newType]) => {
  try {
    if (!newId || newType !== 'Group') {
      currentGroupMemberCount.value = undefined
      return
    }
    
    const normalizeGroupId = (id: string) => id.replace(/^group_/i, '').trim().toLowerCase()
    const normalizedTargetId = normalizeGroupId(newId)
    const chat = recentChatUsers.value?.find(u => {
      if (!u?.id) return false
      const normalizedUId = normalizeGroupId(u.id)
      return u.id === newId || normalizedUId === normalizedTargetId
    })
    
    const memberCountFromChat = (chat as any)?.member_count
    const cached = groupMemberCountCache.value.get(newId)
    if (cached && Date.now() - cached.timestamp < GROUP_MEMBER_COUNT_CACHE_DURATION && cached.count > 0) {
      currentGroupMemberCount.value = cached.count
      return
    }
    
    if (memberCountFromChat !== undefined && memberCountFromChat !== null && memberCountFromChat > 0) {
      currentGroupMemberCount.value = memberCountFromChat
      groupMemberCountCache.value.set(newId, {
        count: memberCountFromChat,
        timestamp: Date.now()
      })
    }
    
    const shouldFetchFromAPI = 
      memberCountFromChat === undefined || 
      memberCountFromChat === null || 
      memberCountFromChat === 0 ||
      !cached ||
      (cached && Date.now() - cached.timestamp >= GROUP_MEMBER_COUNT_CACHE_DURATION)
    
    if (shouldFetchFromAPI) {
      ;(async () => {
        try {
          const { getGroup } = await import('../services/im-group')
          const groupInfo = await getGroup(newId)
          if (groupInfo && groupInfo.member_count !== undefined && groupInfo.member_count !== null && groupInfo.member_count > 0) {
            currentGroupMemberCount.value = groupInfo.member_count
            groupMemberCountCache.value.set(newId, {
              count: groupInfo.member_count,
              timestamp: Date.now()
            })
            console.log('从API获取群组人数:', newId, '人数:', groupInfo.member_count)
          } else {
            console.warn('API返回的群组人数无效:', newId, 'member_count:', groupInfo?.member_count)
          }
        } catch (error) {
          console.warn('获取群组人数失败:', newId, error)
        }
      })()
    }
  } catch (error) {
    console.error('监听群组人数变化时出错:', error)
    currentGroupMemberCount.value = undefined
  }
}, { immediate: true })

// 初始化
onMounted(async () => {
  init()
  
  // 监听通话邀请事件
  const { default: websocketService } = await import('../services/websocket')
  
  // 监听通话取消事件
  websocketService.on('call_cancel', async (data: any) => {
    console.log('📞 收到通话取消事件（ChatWindow）:', {
      fromUserId: data.fromUserId,
      messageId: data.messageId,
    })
    
    // 检查是否是当前通话对象
    if (currentTargetId.value === data.fromUserId) {
      // 结束当前通话
      handleCallEndedWrapper()
      console.log('已自动结束通话（收到对方取消消息）')
    }
  })
  
  websocketService.on('call_invite', async (data: any) => {
    console.log('📞 收到通话邀请事件（ChatWindow）:', {
      fromUserId: data.fromUserId,
      messageId: data.messageId,
      timestamp: data.timestamp,
      timeout: data.timeout,
    })
    
    // 检查通话邀请是否已过期
    const timeout = data.timeout || 60
    const messageTimestamp = data.timestamp || data.timestamp_ms || data.created_at
    
    if (messageTimestamp) {
      const messageTime = typeof messageTimestamp === 'number' 
        ? (messageTimestamp > 1000000000000 ? messageTimestamp : messageTimestamp * 1000) // 处理秒级和毫秒级时间戳
        : new Date(messageTimestamp).getTime()
      const now = Date.now()
      const expireTime = messageTime + (timeout * 1000) // 消息时间 + 超时时间（毫秒）
      const timeDiff = now - messageTime // 消息发送时间距离现在的时间差（毫秒）
      
      // 检查时间戳是否是未来的时间（可能是系统时间错误）
      if (messageTime > now + 60000) {
        console.log('通话邀请时间戳异常（未来时间），忽略:', {
          messageTime: new Date(messageTime).toISOString(),
          now: new Date(now).toISOString(),
          timeDiff: `${Math.floor((messageTime - now) / 1000)}秒`
        })
        return // 忽略异常时间戳
      }
      
      // 重要：先检查是否已过期（当前时间 > 消息时间 + 超时时间）
      // 这是最严格的判断：如果消息已经过期，无论是实时推送还是离线加载，都不应该显示弹窗
      if (now > expireTime) {
        console.log('通话邀请已过期，忽略:', {
          messageTime: new Date(messageTime).toISOString(),
          expireTime: new Date(expireTime).toISOString(),
          now: new Date(now).toISOString(),
          timeout: `${timeout}秒`,
          expiredBy: `${Math.floor((now - expireTime) / 1000)}秒`,
          timeDiff: `${Math.floor(timeDiff / 1000)}秒`
        })
        return // 已过期，不显示弹窗
      }
      
      // 重要：如果消息是离线消息（从数据库加载的），不应该显示弹窗
      // 判断标准：如果消息发送时间距离现在超过10秒，认为是离线消息
      // 因为实时推送的消息通常会在几秒内到达，超过10秒的消息很可能是从数据库加载的离线消息
      // 这样可以避免用户上线后，加载离线消息时弹出过期的通话邀请
      // 使用10秒而不是超时时间的一半，因为即使消息未过期，如果已经超过10秒，用户很可能已经错过了
      const offlineThreshold = 10 * 1000; // 10秒（毫秒）- 更严格的阈值
      if (timeDiff > offlineThreshold) {
        console.log('🚫 这是离线通话邀请消息（从数据库加载），不显示弹窗（只存储，不推送）:', {
          messageTime: new Date(messageTime).toISOString(),
          now: new Date(now).toISOString(),
          timeDiff: `${Math.floor(timeDiff / 1000)}秒`,
          timeout: `${timeout}秒`,
          offlineThreshold: `${Math.floor(offlineThreshold / 1000)}秒`,
          messageId: data.messageId,
          fromUserId: data.fromUserId,
          reason: '离线消息，用户不在线时发送，超过10秒后无意义'
        })
        return // 离线消息，不显示弹窗
      }
    } else {
      // 如果没有时间戳，为了安全，也忽略（可能是历史消息）
      console.log('通话邀请没有时间戳，可能是历史消息，忽略')
      return
    }
    
    console.log('显示通话邀请弹窗，来自:', data.fromUserId)
    
    // 获取发送者用户名
    let fromUserName = data.fromUserName || ''
    if (!fromUserName) {
      // 尝试从好友列表或用户列表获取
      const friend = friendList.value.find(f => 
        (f.user || f).open_id === data.fromUserId || 
        (f.user || f).id === data.fromUserId
      )
      if (friend) {
        fromUserName = friend.name || (friend.user || friend).name || ''
      } else {
        const user = userList.value.find(u => 
          u.open_id === data.fromUserId || u.id === data.fromUserId
        )
        if (user) {
          fromUserName = user.name || ''
        }
      }
    }
    
    // 如果还是找不到用户名，使用用户ID
    if (!fromUserName) {
      fromUserName = data.fromUserId || '未知用户'
    }
    
    callInviteData.value = {
      fromUserId: data.fromUserId,
      fromUserName,
      isVoiceOnly: data.isVoiceOnly !== false,
      messageId: data.messageId,
      timeout: timeout,
    }
  })
  // 监听消息变化，自动滚动到底部
  watch(currentMessages, () => {
    scrollToBottomWrapper()
  }, { deep: true })
  
  // 跟踪 currentTargetId 是否刚刚变化（用于区分用户主动打开和登录后的自动更新）
  let isTargetIdJustChanged = false
  
  // 监听目标切换，自动滚动到底部并标记为已读
  watch(currentTargetId, (newTargetId, oldTargetId) => {
    // 只有在 targetId 真正变化时才标记为已读（不包括从 null 到 null 的情况）
    if (newTargetId && newTargetId !== oldTargetId) {
      isTargetIdJustChanged = true
      nextTick(() => {
        // 延迟一点确保消息已渲染
        setTimeout(() => {
          scrollToBottomWrapper()
          // 再次延迟，确保消息完全加载和渲染（包括离线消息）
          setTimeout(() => {
            scrollToBottomWrapper()
            // 标记为已读（打开窗口即视为已读）
            // 确保 chatId 已经准备好
            if (currentChatId.value && messageListRef.value?.markAsRead) {
              console.log('📖 打开窗口，立即标记为已读:', {
                targetId: newTargetId,
                chatId: currentChatId.value,
              })
              messageListRef.value.markAsRead()
            }
            // 再次延迟标记，确保离线消息加载完成后也能标记为已读
            setTimeout(() => {
              if (currentChatId.value && messageListRef.value?.markAsRead) {
                console.log('📖 延迟标记为已读（确保离线消息加载完成）:', {
                  targetId: newTargetId,
                  chatId: currentChatId.value,
                })
                messageListRef.value.markAsRead()
              }
            }, 500)
            // 重置标志，避免后续的 currentChatId 变化触发
            setTimeout(() => {
              isTargetIdJustChanged = false
            }, 2000)
          }, 300)
        }, 200)
      })
    }
  })
  
  // 同时监听 currentChatId 变化，确保在 chatId 准备好后标记为已读
  // 但只在用户主动打开聊天窗口时触发（通过 isTargetIdJustChanged 标志判断）
  watch(currentChatId, (newChatId, oldChatId) => {
    if (newChatId && newChatId !== oldChatId && isTargetIdJustChanged) {
      nextTick(() => {
        setTimeout(() => {
          if (messageListRef.value?.markAsRead) {
            console.log('📖 chatId 准备好后，立即标记为已读:', {
              chatId: newChatId,
            })
            messageListRef.value.markAsRead()
          }
          // 再次延迟标记，确保离线消息加载完成后也能标记为已读
          setTimeout(() => {
            if (messageListRef.value?.markAsRead) {
              console.log('📖 chatId 准备好后，延迟标记为已读（确保离线消息加载完成）:', {
                chatId: newChatId,
              })
              messageListRef.value.markAsRead()
            }
          }, 800)
        }, 500) // 稍微延迟，确保 MessageList 组件已经接收到新的 props
      })
    }
  })
  
  // 注意：不再监听 recentChatUsers 变化来自动标记为已读
  // 因为登录后更新聊天列表时，如果 currentTargetId 有值（可能是从之前会话恢复的），
  // 会错误地触发已读标记，导致未读消息红点消失
  // 已读标记应该只在用户主动打开聊天窗口时触发（通过 currentTargetId 或 currentChatId 变化）
  
  // 监听已读序列号更新事件，刷新聊天列表以更新未读消息数
  const handleReadSequenceUpdated = (event: Event) => {
    const customEvent = event as CustomEvent
    const { chatId, readSequence } = customEvent.detail || {}
    // 延迟一点刷新，确保服务器已经更新了 read_sequence
    setTimeout(() => {
      updateRecentChatUsers().catch(err => {
        console.error('刷新聊天列表失败:', err)
      })
    }, 200)
  }
  window.addEventListener('readSequenceUpdated', handleReadSequenceUpdated)
  
  // 清理事件监听器
  onUnmounted(() => {
    window.removeEventListener('readSequenceUpdated', handleReadSequenceUpdated)
  })
})

onUnmounted(() => {
  cleanup()
})
</script>

<style lang="sass" scoped>
// CSS 变量定义
.im-container
  --left-menu-width: 80px
  --middle-panel-width: 300px
  --middle-panel-min-width: 240px
  --middle-panel-max-width: 400px
  --border-color: rgba(0, 0, 0, 0.08)
  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.04)
  --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08)
  --transition-base: all 0.3s cubic-bezier(0.4, 0, 0.2, 1)

.im-container
  display: flex
  width: 100vw
  height: 100vh
  background: #EDEDED
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif
  overflow: hidden
  color: #191919
  position: relative

// 中间层 - 优化宽度和视觉效果
.middle-panel
  width: var(--middle-panel-width)
  min-width: var(--middle-panel-min-width)
  max-width: var(--middle-panel-max-width)
  background: #FFFFFF
  border-right: 1px solid var(--border-color)
  display: flex
  flex-direction: column
  height: 100vh
  position: relative
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04), 0 0 0 1px rgba(0, 0, 0, 0.02)
  transition: var(--transition-base)
  z-index: 2
  backdrop-filter: blur(10px)
  -webkit-backdrop-filter: blur(10px)

  // 确保 Transition 内的内容正确填充
  > *
    width: 100%
    height: 100%
    display: flex
    flex-direction: column

// 中间聊天区域 - 优化最小宽度
.middle-chat-panel
  flex: 1
  display: flex
  flex-direction: column
  background: #EDEDED
  min-width: 320px
  position: relative
  overflow: hidden
  // 添加微妙的渐变背景
  background: linear-gradient(180deg, #F0F0F0 0%, #EDEDED 100%)

// 聊天窗口 + 详情面板容器（左右分栏）
.chat-with-details-container
  flex: 1
  display: flex
  flex-direction: row
  height: 100%
  overflow: hidden
  background: #EDEDED

// 带详情面板时的聊天窗口
.chat-panel-with-details
  flex: 2
  min-width: 0
  border-right: 1px solid var(--border-color)

// 好友详情面板样式 - 优化视觉效果
.friend-details-panel
  flex: 1
  display: flex
  flex-direction: column
  background: #F7F7F7
  overflow-y: auto
  min-width: 280px
  box-shadow: inset 1px 0 0 var(--border-color)
  // 添加微妙的背景渐变
  background: linear-gradient(180deg, #FAFAFA 0%, #F7F7F7 100%)

.friend-details-content
  flex: 1
  display: flex
  flex-direction: column

// 空状态优化 - 更友好的视觉设计
.empty-chat
  flex: 1
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  color: #666666
  padding: 40px 20px
  text-align: center
  background: linear-gradient(180deg, #F5F5F5 0%, #EDEDED 100%)

  .empty-chat-icon
    margin-bottom: 24px
    opacity: 0.4
    color: #999999
    transition: opacity 0.3s ease, transform 0.3s ease
    filter: grayscale(20%)
    animation: float 3s ease-in-out infinite

  .empty-chat-text
    display: flex
    flex-direction: column
    gap: 8px
    max-width: 300px

  .empty-chat-title
    font-size: 18px
    color: #333333
    font-weight: 500
    letter-spacing: 0.2px
    line-height: 1.4
    margin-bottom: 4px

  .empty-chat-hint
    font-size: 14px
    color: #999999
    font-weight: 400
    letter-spacing: 0.1px
    line-height: 1.5
    opacity: 0.8

@keyframes float
  0%, 100%
    transform: translateY(0px)
  50%
    transform: translateY(-8px)

.chat-panel
  flex: 1
  display: flex
  flex-direction: column
  height: 100%
  background: transparent
  position: relative

// 过渡动画优化 - 更流畅的动画效果
.fade-slide-enter-active,
.fade-slide-leave-active
  transition: var(--transition-base)

.fade-slide-enter-from
  opacity: 0
  transform: translateX(-10px)

.fade-slide-leave-to
  opacity: 0
  transform: translateX(10px)

// 响应式设计优化
@media (max-width: 1200px)
  .im-container
    --middle-panel-width: 280px
    --middle-panel-min-width: 220px
    --middle-panel-max-width: 360px

@media (max-width: 1024px)
  .im-container
    --middle-panel-width: 260px
    --middle-panel-min-width: 200px
    --middle-panel-max-width: 320px

  .middle-chat-panel
    min-width: 280px

@media (max-width: 768px)
  .im-container
    --middle-panel-width: 240px
    --middle-panel-min-width: 200px
    --middle-panel-max-width: 280px

  .middle-chat-panel
    min-width: 240px

  .friend-details-panel
    min-width: 240px

  .empty-chat
    padding: 32px 16px

    .empty-chat-icon
      margin-bottom: 20px

    .empty-chat-text
      font-size: 14px
      max-width: 240px

// 大屏幕优化
@media (min-width: 1600px)
  .im-container
    --middle-panel-width: 320px
    --middle-panel-min-width: 260px
    --middle-panel-max-width: 450px

// 超小屏幕优化（移动端）
@media (max-width: 640px)
  .middle-panel
    position: absolute
    left: var(--left-menu-width)
    top: 0
    bottom: 0
    z-index: 100
    box-shadow: var(--shadow-md)
    transform: translateX(0)
    transition: transform var(--transition-base)

    // 可以添加一个类来控制显示/隐藏
    // &.hidden
    //   transform: translateX(-100%)

  .middle-chat-panel
    min-width: 100%
    width: 100%

// 打印样式优化
@media print
  .middle-panel
    display: none

  .middle-chat-panel
    width: 100%
</style>
